package com.sem.example2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;

public class ServerThread extends Thread {

	private static int number = 0; // 保存本进程的客户计数

	Socket socket = null; // 保存与本线程相关的Socket对象

	private List<SocketBean> socketInfoList = null;
	private SocketBean socketBean = new SocketBean();

	public ServerThread(Socket socket, int clientnum, List<SocketBean> socketInfoList) {

		this.socket = socket;
		this.socketInfoList = socketInfoList;
		socketBean.setSocket(socket);
		this.socketInfoList.add(socketBean);
		number = clientnum;
		System.out.println("当前在线的用户数: " + number);
	}

	public void run() {
		BufferedReader in = null;
		PrintWriter out = null;
		String name = null;

		try {
			// 由Socket对象得到输入流,并构造相应的BufferedReader对象
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream());
			while (!socket.isClosed()) {
				String line = in.readLine();
				if (name == null) {
					name = line;
					socketBean.setName(name);
					System.out.println("[" + name + "]连接到服务器");
				} else {
					System.out.println(line);

					out.println("数据发送成功");
					sendOtherClient(name, line);
					out.flush();
				}
			}
		} catch (Exception e) {
			System.out.println("Error. " + e);
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close(); // 关闭Socket输出流
			}
			if (in != null) {
				try {
					in.close();// 关闭Socket输入流
				} catch (IOException e) {
					System.err.println("Socket输入流关闭异常，失败");
					e.printStackTrace();
				}
			}
			if (socket != null) {
				try {
					socket.close();// 关闭Socket
				} catch (IOException e) {
					System.err.println("Socket关闭异常，失败");
					e.printStackTrace();
				}
			}
		}
	}

	private void sendOtherClient(String name, String line) throws IOException {
		if (socketInfoList != null) {
			for (SocketBean socketInfo : socketInfoList) {
				if (!socketInfo.getName().equals(name)) {
					PrintWriter otherOut = new PrintWriter(socketInfo.getSocket().getOutputStream());
					otherOut.println(line);
					otherOut.flush();
					otherOut.close();
				}

			}
		}
	}
}